<template>
  <div>
    <div class="container">
      <sticky>
        <step v-model="step" background-color='#fbf9fe'>
          <step-item title="开始"></step-item>
          <step-item title="数据"></step-item>
          <step-item title="结束"></step-item>
        </step>
      </sticky>

      <group title="数据" class="weui_cells_form">
        <template>
          <x-input title="长" class="weui_vcode" :disabled="true"
                   :value="this.device_carSize.cwkc ? this.device_carSize.cwkc :0">
            <span slot="right">{{limit[0]}}</span>
          </x-input>
          <x-input title="宽" class="weui_vcode" :disabled="true"
                   :value="this.device_carSize.cwkk? this.device_carSize.cwkk :0">
            <span slot="right">{{limit[1]}}</span>
          </x-input>
          <x-input title="高" class="weui_vcode" :disabled="true"
                   :value="this.device_carSize.cwkg? this.device_carSize.cwkg :0">
            <span slot="right">{{limit[2]}}</span>
          </x-input>
        </template>
        <template v-if="check.rgfc">
          <x-input type="number" title="长(人工)" class="weui_vcode" v-model="hand_carSize.cwkc">
            <span slot="right">{{limit[0]}}</span>
          </x-input>
          <x-input type="number" title="宽(人工)" class="weui_vcode" v-model="hand_carSize.cwkk">
            <span slot="right">{{limit[1]}}</span>
          </x-input>
          <x-input type="number" title="高(人工)" class="weui_vcode" v-model="hand_carSize.cwkg">
            <span slot="right">{{limit[2]}}</span>
          </x-input>
        </template>

        <x-input title="数据" class="weui_vcode" :disabled="true">
          <x-button slot="right" mini type="primary" @click.native.prevent="getDataFromDevice">取数</x-button>
        </x-input>
        <x-switch :style="'background-color: ' + (rgfc !== 1 ? '#f65959':'#9ddbba')" @on-change="handleRgfcChange"
                  :title="'人工复测' + (rgfc !== 1 ? '不符合':'符合')" :disabled="rgfc !== 1" v-model="check.rgfc"></x-switch>

        <x-input title="判定" class="weui_vcode" :disabled="true" :value="isOK === 1 ?'合格':'不合格'">
          <x-button slot="right" mini :type="isOK === 1?'primary':'warn'" @click.native.prevent="handleDataSend">发送
          </x-button>
        </x-input>
        <cell :title="`${$store.state.carInfo.hphm}`"
              :value="`${$store.state.carInfo.jylsh}-${$store.state.carInfo.jycs}`"></cell>

      </group>
      <x-button :type="sbdh.includes(1)?'primary':'default'" @click.native.prevent="handleTakePhoto([1])" :mini="true">
        前抓拍
      </x-button>
      <x-button :type="sbdh.includes(2)?'primary':'default'" @click.native.prevent="handleTakePhoto([2])" :mini="true">
        后抓拍
      </x-button>
      <x-button @click.native.prevent="handleTakePhoto([1,2])" :mini="true">前后抓拍</x-button>
      <x-button @click.native.prevent="handleStartItem" type="primary">项目开始</x-button>
      <x-button @click.native.prevent="handleEndItemPre" type="primary">项目结束</x-button>

    </div>

  </div>
</template>

<script>
  import {Sticky} from 'vux'

  export default {
    name: "Carsize",
    comments: {
      Sticky
    },
    computed: {
      limit() {
        if (!this.carBase) {
          return [
            '无', '无', '无'
          ]
        }
        return [
          `${this.carBase.cwkcLimit[0]} - ${this.carBase.cwkcLimit[1]}`,
          `${this.carBase.cwkkLimit[0]} - ${this.carBase.cwkkLimit[1]}`,
          `${this.carBase.cwkgLimit[0]} - ${this.carBase.cwkgLimit[1]}`,
        ];
      },
      isOK() {
        if (!this.carBase) {
          return 2;
        }
        let carSize = this.check.rgfc ? this.hand_carSize : this.device_carSize;
        if (!carSize) {
          return 2;
        }
        for (const carSizeKey in carSize) {
          if (carSize[carSizeKey] >= this.carBase[carSizeKey + 'Limit'][0] && carSize[carSizeKey] <= this.carBase[carSizeKey + 'Limit'][1]) {
            continue;
          }
          return 2;
        }
        return 1;
      },
      ckgPd() {
        const pd = {};
        let carSize = this.check.rgfc ? this.hand_carSize : this.device_carSize;
        console.log(carSize);
        for (const carSizeKey in carSize) {
          if (carSize[carSizeKey] >= this.carBase[carSizeKey + 'Limit'][0] && carSize[carSizeKey] <= this.carBase[carSizeKey + 'Limit'][1]) {
            pd[carSizeKey + 'pd'] = 1;
            continue;
          }
          pd[carSizeKey + 'pd'] = 0;
        }
        return pd;
      }
    },
    data() {
      return {
        step: 0,
        carSize: null,
        hand_carSize: {cwkc: 0, cwkk: 0, cwkg: 0},
        device_carSize: {cwkc: 0, cwkk: 0, cwkg: 0},
        carBase: null,
        sbdh: [],
        rgfc: 0,
        check: {
          rgfc: false
        }
      }
    },
    methods: {
      handleRgfcChange(value) {
      },
      getLimit() {
        const data = {};
        data.api = this.$api.getCarSizeBase;
        data.data = this.$getBase();
        this.$http.post(this.$store.getters.uri, data)
          .then(res => {
            const {data} = res;
            if (data.code !== 200) {
              this.$error(data.message);
              return;
            }
            this.$success(data.message);
            this.carBase = data.data;
          }).catch(err => console.log(err));
      },
      handleStartItem() {
        const _this = this;
        if (this.step > 0) {
          this.$vux.confirm.show({
            title: '项目已开始,是否覆盖',
            // 组件除show外的属性
            onCancel() {
            },
            onConfirm() {
              _this.step = 0;
              _this.handleStartItem();
            }
          })
        }
        if (this.step !== 0) {
          return;
        }
        let startDate = this.$dataFormat(new Date(), 'YYYY-MM-DD HH:mm:ss');
        this.$request.itemStart.call(this, function (res) {
          const {data} = res;
          if (data.code !== 200) {
            this.$error(data.message);
            return;
          }
          this.step = 1;
          this.$request.connDb.call(this, (res) => {
            const {data} = res;
            if (data.code !== 200) {
              this.$error(data.message);
              return;
            }
            this.$success(data.message);
          }, (e) => {
            this.$error(e);
            console.log(e);
          }, this.$sql.updateStartTime, startDate);
        }, function (error) {
          console.error(error);
          this.$error(error);
        }, startDate);
      },
      handleDataSend() {
        const _this = this;
        if (this.step === 0) {
          this.$error("项目尚未开始");
          return;
        }
        if (!this.device_carSize
          || this.device_carSize.cwkc === 0
          || this.device_carSize.cwkk === 0
          || this.device_carSize.cwkg === 0
        ) {
          this.$error("没有获取到数据");
          return;
        }
        const data = {};
        data.api = this.$api.saveCarSize;
        data.data = this.$getBase();
        for (const key in this.device_carSize) {
          data.data[key] = this.device_carSize[key];
        }
        data.data.sfjsb = '';
        data.data.cwkcrgfc = this.hand_carSize.cwkc ? this.hand_carSize.cwkc : '';
        data.data.cwkkrgfc = this.hand_carSize.cwkk ? this.hand_carSize.cwkk : '';
        data.data.cwkgrgfc = this.hand_carSize.cwkg ? this.hand_carSize.cwkg : '';
        data.data.clwkccpd = this.isOK;
        this.$http.post(this.$store.getters.uri, data)
          .then(res => {
            const {data} = res;
            if (data.code !== 200) {
              this.$error(data.message);
              return;
            }
            this.step = 2
            const param = {};
            const carInfo = _this.$store.state.carInfo;
            param.api = _this.$api.connDb;
            param.data = {
              sql: `if exists(select 1 from tab_carsize where jylsh='${carInfo.jylsh}' and jycs=${carInfo.jycs}) begin update tab_carsize SET cwkcpd=${_this.ckgPd['cwkcpd']},cwkkpd=${_this.ckgPd['cwkkpd']},cwkgpd=${_this.ckgPd['cwkgpd']},cwkc=${_this.device_carSize.cwkc},cwkk=${_this.device_carSize.cwkk},cwkg=${_this.device_carSize.cwkg},cwkcrgfc=${_this.hand_carSize.cwkc},cwkkrgfc=${_this.hand_carSize.cwkk},cwkgrgfc=${_this.hand_carSize.cwkg},sfjsb='',clwkccpd=${_this.isOK},gxsj=CONVERT(varchar,GETDATE(),120),jycs=${carInfo.jycs} WHERE jylsh='${carInfo.jylsh}' and jycs=${carInfo.jycs} end else begin insert into tab_carsize(jyjgbh,jcxdh,jylsh,jyxm,hphm,hpzl,jycs,cwkc,cwkk,cwkg,cwkcrgfc,cwkkrgfc,cwkgrgfc,sfjsb,clwkccpd,cwkcpd,cwkkpd,cwkgpd,gxsj) values ('${carInfo.jyjgbh}',${carInfo.jcxdh},'${carInfo.jylsh}', '${carInfo.jyxm}', '${carInfo.hphm}', '${carInfo.hpzl}', ${carInfo.jycs},${_this.device_carSize.cwkc},${_this.device_carSize.cwkk},${_this.device_carSize.cwkg},${_this.hand_carSize.cwkc},${_this.hand_carSize.cwkk},${_this.hand_carSize.cwkg},'',${_this.isOK},${_this.ckgPd['cwkcpd']},${_this.ckgPd['cwkkpd']},${_this.ckgPd['cwkgpd']},CONVERT(varchar,GETDATE(),120)) end`
            }
            this.$http.post(this.$store.getters.uri, param).then(res => {
              const {data} = res;
              if (data.code !== 200) {
                _this.$error("插入数据库失败:" + data.message);
                return;
              }
              _this.$success(data.message);
            })
            this.$request.connDb.call(this, (res) => {
              const {data} = res;
              if (data.code !== 200) {
                this.$error(data.message);
                return;
              }
              this.$success(data.message, null);
            }, (error) => {
              console.log(error);
            }, this.$sql.updateDataTime);
          })
          .catch(error => {
            console.error(error)
          });
      },
      handleTakePhoto(sbdhs) {
        try {
          if (sbdhs.length === 2) {
            this.takePhoto(1, 2);
            return;
          }
          this.takePhoto(sbdhs[0]);
        } finally {

        }
      },
      takePhoto(sbdh, sbdh2) {
        this.$request.takePhoto.call(this, (res) => {
          const {data} = res;
          if (data.code !== 200) {
            this.$error(data.message);
            return;
          }
          this.$success(sbdh === 1 ? "前拍照成功" : "后拍照成功");
          this.sbdh.push(sbdh);
          if (sbdh2) {
            this.takePhoto(2);
          }
          if (this.sbdh.includes(1) && this.sbdh.includes(2)) {
            this.$request.connDb.call(this, (res) => {
              const {data} = res;
              if (data.code !== 200) {
                this.$error(data.message);
                return;
              }
              this.$success(data.message);
            }, (e) => {
              this.$error(e);
              console.log(e);
            }, this.$sql.updateTakePhotoTime)
          }
        }, (e) => {
          this.$error(e);
          console.error(e);
        }, sbdh);
      },
      handleEndItemPre() {
        this.$request.connDb.call(this, (res) => {
          const {data} = res;
          if (data.code !== 200) {
            this.$error(data.message);
            return;
          }
          const target = data.data[0] || {};
          if (!target.sjsj) {
            this.$error("没有上传数据的记录时间");
            return;
          }
          if (!target.zpsj) {
            this.$error("没有照片记录的时间");
            return;
          }
          if (target.jssj) {
            this.$success('项目已有结束时间');
            this.$router.go(-1);
            return;
          }
          this.handleEndItem();
        }, (e) => {
          this.$error(e);
          console.error(e);
        }, this.$sql.getAllTimeInStateTable);
      },
      handleEndItem() {
        let endDate = this.$dataFormat(new Date(), 'YYYY-MM-DD HH:mm:ss')
        this.$request.itemEnd.call(this, (res) => {
          const {data} = res;
          if (data.code !== 200) {
            this.$error(data.message);
            return;
          }
          this.step = 3;
          this.$request.connDb.call(this, (res) => {
            const {data} = res;
            if (data.code !== 200) {
              this.$error(data.message);
              return;
            }
            this.$success(data.message, null);
            this.$router.go(-1);
          }, (e) => {
            this.$error(e);
            console.error(e);
          }, this.$sql.updateStopItemTime, endDate);
        }, (e) => {
          console.error(e);
          this.$error(e);
        }, endDate);
      },
      getDataFromDevice() {
        const _this = this;
        if (!this.carBase) {
          this.$vux.confirm.show({
            title: '先获取限值的数据',
            // 组件除show外的属性
            onCancel() {
            },
            onConfirm() {
              _this.step = 0;
              _this.getLimit();
            }
          })
          return;
        }
        const data = {};
        data.api = this.$api.getCarSize;
        data.data = this.$getBase();
        this.$http.post(this.$store.getters.uri, data).then(res => {
          const {data: _data} = res;
          if (_data.code !== 200) {
            this.$error(_data.message);
            return;
          }
          _this.rgfc = _data.data.fhrgfc - 0 | 0;
          delete _data.data.fhrgfc;
          _this.carSize = _data.data;
          _this.device_carSize = _data.data;
          if (_this.rgfc !== 1) {
            _this.check.rgfc = false;
          }
        })
      },
      getHistory() {
        this.$request.connDb.call(this, (res) => {
          const {data} = res;
          if (data.code !== 200) {
            this.$error(data.message);
            return;
          }
          let datum = data.data[0] || 0;
          if (!datum || !datum.extData) {
            return;
          }
          try {
            let parse = JSON.parse(datum.extData);
            if (parse) {
              let {hand_carSize, device_carSize, rgfc, check_rgfc} = parse;
              if (device_carSize != null) {

                this.device_carSize = device_carSize;
              }
              if(hand_carSize != null) {
                this.hand_carSize = hand_carSize;
              }
              this.rgfc = rgfc ? rgfc : 0;
              this.check.rgfc = check_rgfc ? check_rgfc : false;
            }
          } catch (e) {
            this.$error(e);
            console.error(e)
          }
          this.$success(data.message);
        }, (e) => {
          this.$error(e);
          console.error(e);
        }, this.$sql.getExtDataInItemStatusTable);
      },
      dataInsertExtData(extData) {
        const data = {};
        data.api = 404;
        data.data = {
          sql: this.$sql.updateExtDataInItemStatusTable.call(this, {
            extData: JSON.stringify(extData)
          })
        }
        this.$http.post(this.$store.getters.uri, data)
          .then((res) => {
            const {data} = res;
            if (data.code !== 200) {
              this.$error(data.message);
              return;
            }
            this.$success(data.message);
          })
          .catch((e) => {
            this.$error(e);
            console.log(e);
          });
      }
    },
    created() {
      this.getHistory();
      this.getLimit();
      if (this.$store.state.carInfo.kssj) {
        this.step = 1;
      }
    },
    beforeRouteLeave(to, from, next) {
      if (this.carSize) {
        let parse = {};
        parse.device_carSize = this.device_carSize;
        parse.hand_carSize = this.hand_carSize;
        parse.rgfc = this.rgfc;
        parse.check_rgfc = this.check.rgfc;
        this.dataInsertExtData(parse);
      }

      next();
    }
  }
</script>

<style scoped>
  .container {
    padding: 6px;
  }
</style>
